// tabbar模块
const state = {
	current: 0,
	list: [{
			icon: "cus-icon cus-icon-home",
			text: "首页",
			pagePath: "/pages/home/home",
		},
		{
			icon: "cus-icon cus-icon-qrdcode",
			text: "二维码",
			pagePath: "/pages/qrdcode/qrdcode",
		},
		{
			icon: "cus-icon cus-icon-schedule",
			text: "日程",
			pagePath: "/pages/schedule/schedule",
		},
		{
			icon: "cus-icon cus-icon-my",
			text: "我的",
			pagePath: "/pages/my/my",
		},
	],
};

const mutations = {
	SET_TABBAR_INDEX(state, index) {
		state.current = index;
	},
	// 添加新的tabbar项
	ADD_TABBAR_ITEM(state, item) {
		state.list.push(item);
	},
	// 在指定位置插入tabbar项
	INSERT_TABBAR_ITEM(state, {
		item,
		index
	}) {
		if (index >= 0 && index <= state.list.length) {
			state.list.splice(index, 0, item);
		} else {
			state.list.push(item);
		}
	},
	// 更新tabbar项
	UPDATE_TABBAR_ITEM(state, {
		index,
		item
	}) {
		if (index >= 0 && index < state.list.length) {
			state.list.splice(index, 1, {
				...state.list[index],
				...item
			});
		}
	},
	// 移除tabbar项
	REMOVE_TABBAR_ITEM(state, index) {
		if (index >= 0 && index < state.list.length) {
			state.list.splice(index, 1);
			// 如果当前选中的索引大于或等于被删除的索引，需要调整
			if (state.current >= index) {
				// 确保current不会小于0
				state.current = Math.max(0, state.current - 1);
			}
		}
	},
	// 替换整个tabbar列表
	SET_TABBAR_LIST(state, list) {
		state.list = list;
		// 确保current不会超出新列表范围
		if (state.current >= list.length) {
			state.current = list.length > 0 ? list.length - 1 : 0;
		}
	},
};

const actions = {
	switchTabbar({
		commit
	}, index) {
		commit("SET_TABBAR_INDEX", index);
	},
	// 添加新的tabbar项
	addTabbarItem({
		commit
	}, item) {
		commit("ADD_TABBAR_ITEM", item);
	},
	// 在指定位置插入tabbar项
	insertTabbarItem({
		commit
	}, {
		item,
		index
	}) {
		commit("INSERT_TABBAR_ITEM", {
			item,
			index
		});
	},
	// 更新tabbar项
	updateTabbarItem({
		commit
	}, {
		index,
		item
	}) {
		commit("UPDATE_TABBAR_ITEM", {
			index,
			item
		});
	},
	// 移除tabbar项
	removeTabbarItem({
		commit
	}, index) {
		commit("REMOVE_TABBAR_ITEM", index);
	},
	// 替换整个tabbar列表
	setTabbarList({
		commit
	}, list) {
		commit("SET_TABBAR_LIST", list);
	},
};

const getters = {
	tabbarList: (state) => state.list,
	currentTabIndex: (state) => state.current,
	// 获取当前选中的tabbar项
	currentTabItem: (state) => state.list[state.current] || null,
	// 获取tabbar列表长度
	tabbarLength: (state) => state.list.length,
	// 根据索引获取特定的tabbar项
	getTabbarItem: (state) => (index) => {
		return index >= 0 && index < state.list.length ? state.list[index] : null;
	},
	// 根据路径查找tabbar项的索引
	findTabbarIndexByPath: (state) => (path) => {
		return state.list.findIndex((item) => item.pagePath === path);
	},
};

export default {
	namespaced: true,
	state,
	mutations,
	actions,
	getters,
};